package co.fitstart.data.handler.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.http.Consts;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.web.support.HttpResult;

import co.fitstart.data.entity.BillData;
import co.fitstart.data.handler.LjzClientOrderHandler;
import co.fitstart.data.utils.JsonUtils;
import co.fitstart.data.utils.SignUtils;
import co.fitstart.entity.order.Order;

/**
 * 陆家嘴购阿购接口处理类
 * @author haiyan_xiao
 *
 */
@Component("ljzClientOrderHandler")
public class LjzClientOrderHandlerImpl implements LjzClientOrderHandler {
    private static final Logger logger = LoggerFactory.getLogger(LjzClientOrderHandler.class);
    
    @Value("#{goago['url']}")
    private String url;

    @Value("#{goago['add_data_method']}")
    private String addDataMethod;

    @Value("#{goago['appkey']}")
    private String appKey;

    @Value("#{goago['appsecret']}")
    private String appSecret;

    @Value("#{goago['mac']}")
    private String terminalNumber;

    /*
     * (non-Javadoc)
     * @see co.fitstart.data.handler.LjzClientOrderHandler#addData(co.fitstart.entity.order.Order)
     */
    @SuppressWarnings("unchecked")
    public HttpResult addData(Order order) {
        Map<String, String> map = new HashMap<>();
        map.put("method", addDataMethod);
        map.put("timestamp", DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
        map.put("messageFormat", "json");
        map.put("appKey", appKey);
        map.put("v", "1.0");
        map.put("signMethod", "MD5");
        map.put("data", JsonUtils.toJson(new BillData(terminalNumber, order)));

        HttpResult httpResult = new HttpResult();

        try {
            String sign = SignUtils.sign(appSecret, map);
            map.put("sign", sign);
            
            URIBuilder builder = new URIBuilder(url);
            
            Form form = Form.form();
            Set<String> keys = map.keySet();
            for(String key : keys) {
                form.add(key, map.get(key));
            }
            
            Response response = Request.Post(builder.build()).bodyForm(form.build()).connectTimeout(10000).socketTimeout(10000).execute();
            String responseBody = response.returnContent().asString(Consts.UTF_8);

            Map<String, String> result = JSON.parseObject(responseBody, Map.class);
            
            if("OPEN_SUCCESS".equals(result.get("rescode"))) {
                httpResult.success().message("账单导入成功");
            } else {
                logger.error("LjzClientOrderHandlerImpl#addData() - Requesting add data encounters error. The error code is {} and error message is {}.", result.get("rescode"), result.get("resmsg"));
                httpResult.fail().message(result.get("resmsg"));
            }
        } catch (Exception e) {
            logger.error("#post order to goago occurs error", e);
            httpResult.fail().message("账单导入失败");
        }
        
        return httpResult;
    }

}
